Technical Q&A HW52
Converting a numeric string to a number under Forth


Q: How do I convert a numeric string to a number under Forth?

A: Try this colon definition X below. Note that X expects an address and length on the stack as its argument.

: x  ( addr len -- true| n false ) $number if abort" nan" then cr ." number = " . ;  ok
  

Enter the string "123" then enter x.

0 > " 123" x
number = 123  ok

X determined the string was indeed a number string, so the output was the number 123. Now try a non-numeric string:

0 > " wrong" x
nan
ok

nan stands for "not a number" as expected. Now let's enter the number 123.

0 > 123 x
DEFAULT CATCH!, code=300 at   %SRR0: ff80bed0   %SRR1: 0000b030
 ok

Since X expected a numeric string which has an address and length and 123 is a single parameter, the Forth interpreter aborted the word X and cleared the stack.


[Mar 29 1999]


Developer Documentation | Technical Notes | Development Kits | Sample Code